class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        srand(time(NULL));
        return mysort(nums,0,nums.size()-1,k);
    }

    int mysort(vector<int>& nums,int left,int right,int k)
    {
        if(left==right) return nums[left];
        int key=getrand(nums,left,right);
        int l=left-1;
        int r=right+1;
        int i=left;
        while(i<r)
        {
            if(nums[i]>key)
            {
                swap(nums[--r],nums[i]);
            }
            else if(nums[i]==key)
            {
                ++i;
            }
            else if(nums[i]<key)
            {
                swap(nums[++l],nums[i++]);
            }
        }

        int a=l-left+1;
        int b=r-l-1;
        int c=right-r+1;
        if(c>=k)
        {
            return mysort(nums,r,right,k);
        }
        else if(b+c>=k)
        {
            return key;
        }
        else
        {
            return mysort(nums,left,l,k-b-c);
        }
    }

    int getrand(vector<int>& nums,int l,int r)
    {
        return nums[rand()%(r-l+1)+l];
    }
};
